package com.open.launcher.utils

import android.text.TextUtils
import android.util.Log


/**
 * Log封装
 */
object KLog {

    private const val TAG_DEFAULT = "papa"
    private const val NULL_TIPS = "Log with null object"

    private const val DEFAULT_MESSAGE = "execute"
    private const val PARAM = "Param"
    private const val NULL = "null"
    private const val SUFFIX = ".java"

    private const val STACK_TRACE_INDEX_4 = 4
    private const val STACK_TRACE_INDEX_5 = 5

    private const val V = 0x1
    private const val D = 0x2
    private const val I = 0x3
    private const val W = 0x4
    private const val E = 0x5
    private const val A = 0x6

    private var globalTag = ""
    private var isShowTag = true

    @JvmStatic
    fun init(isShow: Boolean, tag: String) {
        isShowTag = isShow
        globalTag = tag
    }

    @JvmStatic
    fun d() {
        printLog(D, null, DEFAULT_MESSAGE)
    }

    @JvmStatic
    fun d(msg:String) {
        printLog(D, null, msg)
    }

    @JvmStatic
    fun e(msg: String) {
        printLog(E, null, msg)
    }

    private fun printLog(type: Int, tagStr: String?, msg: String) {
        if (!isShowTag) {
            return
        }
        val contents = wrapperContent(STACK_TRACE_INDEX_5, tagStr, msg)
        val tag = contents!![0]
        val msg = contents[1]
        val headString = contents[2]
        when (type) {
            D -> {
                Log.d(tag, "$headString$msg")
            }
            E -> {
                Log.e(tag, "$headString$msg")
            }
        }
    }

    private fun wrapperContent(stackTraceIndex: Int, tagStr: String?, msg: String): Array<String?>? {
        val stackTrace = Thread.currentThread().stackTrace
        val targetElement = stackTrace[stackTraceIndex]
        var className = targetElement.className
        val classNameInfo = className.split("\\.").toTypedArray()
        if (classNameInfo.isNotEmpty()) {
            className = classNameInfo[classNameInfo.size - 1] + SUFFIX
        }
        if (className.contains("$")) {
            className = className.split("\\$").toTypedArray()[0] + SUFFIX
        }
        val methodName = targetElement.methodName
        var lineNumber = targetElement.lineNumber
        if (lineNumber < 0) {
            lineNumber = 0
        }
        var tag = tagStr ?: className
        if (globalTag.isEmpty() && TextUtils.isEmpty(tag)) {
            tag = TAG_DEFAULT
        } else if (globalTag.isNotEmpty()) {
            tag = globalTag
        }
        val msg: String = msg
        val headString = "[($className:$lineNumber)#$methodName] "
        return arrayOf(tag, msg, headString)
    }

}